import {
  Config
} from 'config.js';

class Token {
  constructor() {
    console.log(this)
    this.verifyUrl = Config.restUrl + '/api/wechat/mp/verify';
    this.tokenUrl = Config.restUrl + '/api/login/get_openid';
  }

  verify(resetGlobalData) {
    var token = wx.getStorageSync('token');
    console.log(token)
    if (!token) {
      //wx.login
      this.login(resetGlobalData);
    } else {
      this._verifyFromServer(token, resetGlobalData);
    }
  }

  // 携带令牌去服务器校验令牌
  _verifyFromServer(token, resetGlobalData) {
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method: 'POST',
      header: {
        'cojwt': token
      },
      success: function(resp) {
        var res = resp.data
        if (res.state != "ok") {
          //清空token
          wx.removeStorageSync('token')          
          that.login(resetGlobalData)
        }
      }
    })
  }

  // 从服务器获取token
  login(resetGlobalData) {
    var that = this;
    wx.login({
      success: function(loginRes) {
        let code = loginRes.code

        //获取用户开放数据
        wx.request({
          url: 'http://192.168.1.108/api/wechat/mp/code2session?code=' + code,
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: sessionRes => {
            var res = sessionRes.data;
            if (res.state == "ok") {
              if (res.auth) {
                //已授权
                wx.setStorageSync('sessionId', res.sessionId)
                wx.setStorageSync('token', res.token)
                var userInfo = {
                  nickName: res.nickName,
                  avatarUrl: res.avatarUrl
                };
                //持久化用户数据
                wx.setStorageSync('userInfo', userInfo)
                //重置全局变量
                resetGlobalData(userInfo)
              } else {
                //未授权
                //发起获取用户信息
                wx.setStorageSync('sessionId', res.sessionId)

                that._getUserInfo(resetGlobalData, res.sessionId)
              }
            } else {
              wx.showToast({
                title: '愈历登录异常',
                icon: 'warn',
                duration: 1000
              })
            }
          }
        })

      }
    })
  }

  //发起获取用户信息
  _getUserInfo(resetGlobalData, sessionId) {
    var that = this;
    // 获取用户信息
    wx.getSetting({
      success: authRes => {
        if (authRes.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: userInfoRes => {
              //持久化用户数据
              wx.setStorageSync('userInfo', userInfoRes.userInfo)
              //重置全局变量
              resetGlobalData(userInfoRes.userInfo)

              userInfoRes.sessionId = sessionId;

              //获取开放数据
              //返回服务端解密开放数据
              that._decryptUserInfo(userInfoRes);

            }
          })
        }
      }
    })
  }

  //返回服务端解密开放数据
  _decryptUserInfo(userInfoRes) {
    wx.request({
      url: 'http://192.168.1.108/api/wechat/mp/decryptUserInfo',
      method: 'POST',
      data: JSON.stringify(userInfoRes),
      header: {
        'content-type': 'application/json'
      },
      success: function(res2) {
        var res = res2.data;
        if (res.state == "ok") {
          wx.setStorageSync('token', res.token)
        }
      }
    })
  }


}

export {
  Token
};